package zooin.net;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Login extends Activity {
	public static Activity activity; 
	public static String INTENT_VAL ="";
	public static String INTENT_USER="userid";
	private EditText id;
	private EditText passwd;
	ConnectivityManager cManager;   
	NetworkInfo mobile;   
	NetworkInfo wifi;
	public function fc = new function();
	private SharedPreferences pref =null;

    String thisIP,pId,UserPWD, thisM, loginok;
    public static String handlerS ="ok";
    /////////////
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_s);
        
	       // 입력된 정보를 저장하기 위해 Class & Method 호출
     		pref    = getSharedPreferences("userInfo",Activity.MODE_PRIVATE);
     		thisIP	= pref.getString("thisIP", "");
     		pId 	= pref.getString("pId", "");
     		UserPWD 	= pref.getString("UserPWD", "");  
            thisM = pref.getString("thisM", "");  
            loginok = pref.getString("loginok", "");   		

     	//	Toast.makeText(Login2.this, "pId:"+pId,Toast.LENGTH_LONG).show();	
     		
        //로그인,회원가입
    	Button userLogin = (Button) findViewById(R.id.userLogin);
    	Button userMem = (Button)findViewById(R.id.userMem);
    	EditText userId = (EditText)findViewById(R.id.id);
    	EditText userPw = (EditText)findViewById(R.id.passwd);
    	
    	if(pId=="" | pId== null){
    	userLogin.setText("로그인");
     	userLogin.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		confirm();
        	}
        });
    	userMem.setText("회원가입");
    	userMem.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		Intent intent2 = new Intent(Login.this,MemberJoin.class);
				startActivity(intent2);
        	}
        });
    	}else{
    		userId.setText(pId);
    		userPw.setText(UserPWD);
        	userLogin.setText("로그아웃");
         	userLogin.setOnClickListener(new View.OnClickListener(){
            	public void onClick(View v){
            	Toast.makeText(Login.this,pId +"님 로그아웃 되셨습니다", 0).show();
       			 pref = getSharedPreferences("userInfo", MODE_PRIVATE); 
       	    		SharedPreferences.Editor editor = pref.edit(); 
       	    		  editor.remove("pUserIdx");
       			      editor.remove("pId");
       			      editor.remove("pName");
       			      editor.remove("pDeviceIdx");
       			      editor.remove("pDeviceName");
       			      editor.commit(); 
       			      onCreate(null); 
            	}
            	
            });
        	userMem.setText("회원정보 수정");
         	userMem.setOnClickListener(new View.OnClickListener(){
            	public void onClick(View v){
            		Intent intent2 = new Intent(Login.this,EditMemberJoin.class);
    				startActivity(intent2);
            	}
            });
    	}
   
    	
       
    }

    //로그인 처리
    public void confirm(){
    	id = (EditText) findViewById(R.id.id);
	    String UserID = id.getText().toString();
    	passwd = (EditText) findViewById(R.id.passwd);
	    String UserPWD = passwd.getText().toString();
	    String html;
	    
  

	   	if ( !checkID())
    	{
    		return ;
    	}
    	if( "".equals(UserPWD) || UserPWD == null){
    		Toast.makeText(Login.this, "패스워드를 입력하세요.", Toast.LENGTH_SHORT).show();
    		return ;
    	}else{
    		fc.createThreadAndDialog(Login.this); // 진행바 호출
    		try {
    			html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=1000&userid="+ UserID +"&userpwd="+UserPWD+"&deviceType="+thisM,this);
            	int htmlValue1 = Integer.parseInt(html.split("ú")[0]);	
            	
            	if(htmlValue1 > 0){
            		String htmlValue=html.split("ú")[1];
            		String pUserIdx = htmlValue.split("")[0].toString();
            		String pId = htmlValue.split("")[1].toString();
            		String pName = htmlValue.split("")[2].toString();
    		        String pDeviceIdx = htmlValue.split("")[3].toString();
    		        String pDeviceName = htmlValue.split("")[4].toString();
    		       // Toast.makeText(Login2.this, "pUserIdx:"+pUserIdx, 0).show();
    		       // Toast.makeText(Login2.this, "pName:"+pName, 0).show();
    		        if(loginok.equals(handlerS)){

     	  				//Toast.makeText(Login.this, "이미시작", 0).show();
  	    		       }else{
  	    		    	    //핸들러 호출하기
       	  				handler.sendEmptyMessage(REPORT_MSG);
       	  				//Toast.makeText(Login.this, "재생전환 핸들러 시작"+loginok, 0).show();
       	  				loginok="ok";
  	    		     }
    		        
    		        
    		        //저장을 위해 Edit객체 호출
    		        SharedPreferences.Editor editor = pref.edit();
	    		        // 값 입력
	    		        editor.putString("pUserIdx", pUserIdx);
	    		        editor.putString("pId", pId);
	    		        editor.putString("pName", pName);
	    		        editor.putString("pDeviceIdx", pDeviceIdx);
	    		        editor.putString("pDeviceName", pDeviceName);
	    		        editor.putString("thisIP", thisIP);
	    		        editor.putString("UserPWD", UserPWD);
	    		        editor.putString("loginok", loginok);
	    		        // 변경된 값 저장
	    		        editor.commit();
    		       	    		   
            		//intent 생성 및 값 전달
            		Intent intent = new Intent(Login.this, setList.class);
            	  //  Toast.makeText(Login2.this, "UserID:"+UserID, 0).show();
    	        	intent.putExtra(INTENT_USER, UserID);
        	    	startActivity(intent);
        	    	Login.this.finish();
        	    	
            	}else{
            		Toast.makeText(Login.this, "패스워드가 일치하지 않습니다.\n다시 입력해주세요." , Toast.LENGTH_SHORT).show();	
            		fc.closeThreadAndDialog();
            		//dismissDialog();
            	}//htmlValue1 > 0
			} catch (Exception e) {}
        	
    	}
    	
		return ;
    }
    
    

    
    
    //로그인 값 체크
    public boolean checkID(){
 	   String UserID = id.getText().toString();
 	   boolean retVal = false;
        
 	       if(!UserID.replace(" ", "").equals("") ){	//공백 및 스페이스 체크
 		       String html;
 		       try {
 		    	   
 		 		    	   
 		    	   html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=1005&userid="+ UserID,this);
 		    	   if (html.indexOf("error") >= 0){
 		    		  Toast.makeText(Login.this, "서버가 일치적으로 동작하지 않습니다." , Toast.LENGTH_SHORT).show();
 		    	   }
 		    	   
 		    	   String GetID = html.split("ú")[0].toString();
 		    		
 		    	   if(!fc.checkFormValid(UserID)){
 	 		    	   Toast.makeText(Login.this, "ID를 정확히 입력하세요.", Toast.LENGTH_SHORT).show();	//숫자와 영문조합만 가능
 	 		    	   id.requestFocus();
 	 		    	   retVal = false;
 	 		       }else{	       
 	 			       if(GetID.charAt(0) == '1'){
 	 			    	  passwd.requestFocus();
 	 			    	  retVal = true;
 	 			       }else{
 	 			    	   //password 창으로 focus!!
 	 			    	   Toast.makeText(Login.this, "존재하지 않는 ID입니다.\n회원가입을 하시기 바랍니다.", Toast.LENGTH_SHORT).show();
 	 			    	   id.requestFocus();
 	 			    	   retVal = false;
 	 			       }
 	 		       }
 		    		
				} catch (Exception e) {}
 		      
 	       }
 	       else{ 
 	    	   Toast.makeText(Login.this, "ID를 입력하세요", Toast.LENGTH_SHORT).show();
 	    	   id.requestFocus();
 	    	   retVal = false;
 	       }
 	       return retVal;
     }

    	
    @Override
    public void onBackPressed() {
    	
		Intent intent = new Intent(Login.this,setList.class);
		startActivity(intent);
		Login.this.finish();
	}

    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
    
    
    ////////재생 전환 이벤트 받아오기 위한 핸들러
    private static final int REPORT_MSG=0;
	   //핸들러 정의 하기
	    Handler handler=new Handler(){
	    	public void handleMessage(android.os.Message msg){
	    		
	    		switch (msg.what) {
				case REPORT_MSG:{
					try {
		    		     SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
		    		        String pId 			= prefs.getString("pId", "");
		    		        String pDeviceIdx 	= prefs.getString("pDeviceIdx", "");
		    		        String thisIP 		= prefs.getString("thisIP", "");
		    		//	Toast.makeText(Login2.this, "동작중1"+thisIP, Toast.LENGTH_SHORT).show();
		    			String moveScreenCheck = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=4001&deviceIdx="+pDeviceIdx,Login.this);
		        		String ret_code = moveScreenCheck.split("ú")[0].toString();
		        		if (ret_code.equals("1")) {
							//화면전환
		        		//	Toast.makeText(MainCategory.this, "동작중1", Toast.LENGTH_LONG).show();
		        			String moveSrcInfo = moveScreenCheck.split("ú")[1].toString();
		        			String moveidx = moveSrcInfo.split("")[0].toString();
		            		final String playUrl = moveSrcInfo.split("")[1].toString(); // play url
		            		final String playPos = moveSrcInfo.split("")[2].toString();  // pos
		            		
		            	//	final String playTime = moveSrcInfo.split("")[3].toString();  // Total Time
		            		final String playType = moveSrcInfo.split("")[4].toString();  // View Type : VOD / LIVE
		            		final String playId = moveSrcInfo.split("")[5].toString();  // VOD : Contents ID , LIVE : channel id
		            		String moveScreenResult = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=4002&deviceIdx="+pDeviceIdx+"&moveidx="+moveidx,Login.this);
			            		Intent intent = new Intent(Login.this,playchange.class);
				               		intent.putExtra("videouserid", pDeviceIdx);
									intent.putExtra("videoposition", playPos);
									intent.putExtra("videofilename", playUrl);
									intent.putExtra("videotype", playType);
									intent.putExtra("videoid", playId);
									intent.putExtra("postip", thisIP);
							startActivity(intent);
		    			    
		            		
		            			
						}
		        		
					} catch (Exception e) {}
				}break;

				default:
					break;
				}
	    		
	    	
				 handler.sendEmptyMessageDelayed(0, 3000);
				// Toast.makeText(MainCategory.this, "동작중", Toast.LENGTH_LONG).show();
	    	}
	    };
    

}